//
// Created by kriko on 2021/7/2.
//

#include <csapp.h>

void *thread(void *);

volatile long cnt = 0;
sem_t mutex;

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s<niters>\n", argv[0]);
        return -1;
    }
    long niters = 0;
    niters = atoi(argv[1]);

    sem_init(&mutex, 0, 1);
    pthread_t pid_1, pid_2;

    pthread_create(&pid_1, NULL, thread, &niters);
    pthread_create(&pid_2, NULL, thread, &niters);

    pthread_join(pid_1, NULL);
    pthread_join(pid_2, NULL);

    if(cnt != (niters * 2)) {
        printf("Boom! cnt = %ld\n", cnt);
    }else {
        printf("OK! cnt = %ld\n", cnt);
    }

    return 0;
}

void *thread(void *args) {
    long niters = *((long *)args);
    for(auto i = 0L; i < niters; ++i) {
        P(&mutex);
        cnt ++;
        V(&mutex);
    }
    return NULL;
}